/**
 * @title 创建舞台
 */
import Konva from "konva";

export default {
  //创建舞台
  creacteKonva(that) {
    that.container = true;
    that.$store.commit("templateStage/PROSCENIUM", true); //是否开启舞台
    this.CalculateScreensize(that, that.maxW, that.maxH);
    let obj = {
      src: that.BackPicUrl,
    };
    this.creactepicture(that, obj, "back");
  },
  //添加图片
  creactepicture(that, value, type) {
    if (that.historylist.length == 0 && type != "back")
      that.$createstage.saveHistory(that);
    if (that.proscenium) {
      let name, numberImg, picname;
      let draggable = true;
      if (type == "back") {
        draggable = false;
        picname = "背景";
      } else if (type == "pic") {
        that.loadingframe = true;
        picname = value.name;
        that.$store.commit("templateStage/IMGNUM");
      } else if (type == "logo") picname = value.name;
      let img = new Image();
      img.onload = function () {
        that.$store.commit("templateStage/NUMBERREFS", 1);
        let x = that.imgW / 2 - img.width / 2;
        let y = that.imgH / 2 - img.height / 2;
        let new_img = {
          config: {
            width: Number(img.width),
            height: Number(img.height),
            w: img.width,
            h: img.height,
            draggable,
            name: `img${type}${that.numberRefs}`,
            x,
            y,
            image: img,
            opacity: 1,
            strokeEnabled: true,
            filters: [Konva.Filters.Brighten],
            brightness: 0,
            picname,
            z: true, //判断是置于底部还是置于顶部
          },
        };
        that.$store.commit(
          "templateStage/CLICKNAMEREACT",
          `img${type}${that.numberRefs}`
        );

        if (type == "logo") {
          numberImg = that.listlogo.length;
          that.$store.commit("templateStage/LISTLOGO", new_img);
          name = that.listlogo[numberImg].config.name;
          that.$nextTick(() => {
            const node =
              that.$refs[that.listlogo[numberImg].config.name][0].getStage();
            node.cache();
            node.getLayer().batchDraw();
            let name_refs =
              that.$refs[that.listlogo[numberImg].config.name][0].getNode();
            that.$createstage.addTransformerImmediate(that, name_refs, name);
          });
        } else {
          numberImg = that.listImg.length;
          that.$store.commit("templateStage/LISTIMG", new_img);
          name = that.listImg[numberImg].config.name;
          that.$nextTick(() => {
            const node =
              that.$refs[that.listImg[numberImg].config.name][0].getStage();
            node.cache();
            node.getLayer().batchDraw();
            let name_refs =
              that.$refs[that.listImg[numberImg].config.name][0].getNode();
            that.$createstage.addTransformerImmediate(that, name_refs, name);
            that.loadingframe = false;
          });
        }
        if (type != "back") that.$createstage.saveHistory(that);
      };
      img.crossOrigin = "Anonymous";
      img.src = value.src;
    }
    //还未开启舞台
    else return;
  },

  //添加文本框
  creactetext(that, type) {
    if (that.historylist.length == 0) that.$createstage.saveHistory(that);
    let text;
    if (type == "data") text = that.$datatools.formattime();
    else text = "请编辑文本吧";
    let { textfontsize } = that;
    let x = that.imgW / 2 - (textfontsize * 6) / 2;
    let y = that.imgH / 2 - textfontsize / 2;
    that.$store.commit("templateStage/NUMBERREFS", 1);
    let new_note = {
      config: {
        width: textfontsize * 6.2,
        height: textfontsize,
        text,
        fontSize: textfontsize,
        fontStyle: "normal",
        fontFamily: that.textfontFamily,
        draggable: true,
        align: "left",
        name: `con${type}${that.numberRefs}`,
        fill: "#000000",
        x,
        y,
        opacity: 1,
        wrap: "word",
        textDecoration: "normal",
        shadowColor: "#000000",
        shadowOffsetX: 0,
        shadowOffsetY: 0,
        shadowBlur: 0,
        lineHeight: 1.1,
        letterSpacing: 1,
        stroke: "#000000",
        strokeWidth: 0,
        s: that.editbackSize,
        scaleX: 1,
        scaleY: 1,
        lineNum: 1,
        spacingNum: 6,
        verticaltext: false, //是否是竖向排列
        originaltext: text,
      },
    };
    that.$store.commit(
      "templateStage/CLICKNAMEREACT",
      `con${type}${that.numberRefs}`
    );
    let numberNote = that.listNote.length;
    that.$store.commit("templateStage/LISTNOTE", new_note);
    let { name } = that.listNote[numberNote].config;
    that.$createstage.saveHistory(that);
    that.$nextTick(() => {
      let name_refs =
        that.$refs[that.listNote[numberNote].config.name][0].getNode();
      that.$createstage.addTransformerImmediate(that, name_refs, name);
    });
  },
  //添加图片框
  creacteellipse(that, type) {
    if (that.historylist.length == 0) that.$createstage.saveHistory(that);
    that.$store.commit("templateStage/NUMBERREFS", 1);
    let x = parseInt(that.configKonva.width / 2);
    let y = parseInt(that.configKonva.height / 2);
    let new_ellipse = {
      config: {
        width: 120,
        height: 180,
        draggable: true,
        name: `${type}${that.numberRefs}`,
        x,
        y,
        fill: "#ffffff",
        scaleX: 1,
        scaleY: 1,
        opacity: 1,
      },
    };
    that.$store.commit(
      "templateStage/CLICKNAMEREACT",
      `${type}${that.numberRefs}`
    );
    let numberImg = that.listEllipse.length;
    that.$store.commit("templateStage/LISTELLIPSE", new_ellipse);
    let { name } = that.listEllipse[numberImg].config;
    that.$createstage.saveHistory(that);
    that.$nextTick(() => {
      let name_refs =
        that.$refs[that.listEllipse[numberImg].config.name][0].getNode();
      that.$createstage.addTransformerImmediate(that, name_refs, name);
    });
  },
  //添加变换器
  addTransformerImmediate(that, name_refs, name) {
    that.$store.commit("templateStage/TEXTNODE", name_refs);
    //  let selectedShapeName
    that.$store.commit("templateStage/SELECTEDSHAPENAME", name);
    this.updateTransformer(that);
    this.creacteTools(that, name);
  },
  //添加变换器
  updateTransformer(that) {
    let name;
    const transformerNode = that.tr;
    const stage = transformerNode.getStage();
    let { selectedShapeName } = that;
    selectedShapeName = that.$datatools.fragmentreat(selectedShapeName);
    let selectedNode = stage.findOne("." + selectedShapeName);

    if (!selectedNode) {
      // this.creacteTools(that, "");
    }
    if (selectedNode === transformerNode.node()) return;
    if (selectedNode) {
   
      name = selectedNode.VueComponent.oldProps.name;
      //添加变换器 - 判断是否低于背景层级 
      if (that.afterbackimg.indexOf(name) != -1) {
        //再判断一下是否上锁，上锁还是false
        let flag;
        that.listImg.forEach((v) => {
          if (v.config.name == name) return (flag = v.config.draggable);
        });
        if (flag) transformerNode.shouldOverdrawWholeArea(true);
        else transformerNode.shouldOverdrawWholeArea(false);
      } else transformerNode.shouldOverdrawWholeArea(false);

      that.$store.commit("templateStage/MODIFYELE", name);
      transformerNode.borderStroke("#87ceeb");
      if (name.indexOf("data") != -1) {
        transformerNode.enabledAnchors([
          "top-left",
          "top-right",
          "bottom-left",
          "bottom-right",
        ]);
        transformerNode.nodes([selectedNode]);
        selectedNode.on("transform", function () {
          let fontSize;
          if (selectedNode.height() < 0) fontSize = selectedNode.height() * -1;
          else return selectedNode.height();
          selectedNode.setAttrs({
            width: selectedNode.width() * selectedNode.scaleX(),
            scaleX: 1,
            height: selectedNode.height() * selectedNode.scaleY(),
            fontSize,
            scaleY: 1,
          });
        });
      } else if (name.indexOf("text") != -1) {
        transformerNode.enabledAnchors([
          "top-left",
          "top-right",
          "bottom-left",
          "bottom-right",
        ]);
        transformerNode.nodes([selectedNode]);
        selectedNode.on("transform", function () {
          selectedNode.setAttrs({
            width: selectedNode.width(),
            scaleX: selectedNode.scaleX(),
            height: selectedNode.height(),
            scaleY: selectedNode.scaleY(),
          });
        });
      } else if (name.indexOf("img") != -1) {
        transformerNode.enabledAnchors([
          "top-left",
          "top-right",
          "bottom-left",
          "bottom-right",
        ]);
        transformerNode.nodes([selectedNode]);
        selectedNode.on("transform", function () {
          selectedNode.setAttrs({
            width: selectedNode.width(),
            scaleX: selectedNode.scaleX(),
            height: selectedNode.height(),
            scaleY: selectedNode.scaleY(),
          });
        });
      } else if (name.indexOf("ellipse") != -1) {
        transformerNode.enabledAnchors([
          "top-left",
          "top-right",
          "middle-right",
          "middle-left",
          "bottom-left",
          "bottom-right",
        ]);
        transformerNode.nodes([selectedNode]);
        selectedNode.on("transform", function () {
          selectedNode.setAttrs({
            width: selectedNode.width(),
            scaleX: selectedNode.scaleX(),
            height: selectedNode.height(),
            scaleY: selectedNode.scaleY(),
          });
        });
      } else this.delTransformer(that);
      transformerNode.rotateEnabled(true);
      if (that.keyele) {
        that.keyele.forEach((v) => {
          if (v == selectedShapeName) {
            transformerNode.enabledAnchors([]);
            transformerNode.borderStroke("red");
            transformerNode.rotateEnabled(false);
          }
        });
      }
      if (name.indexOf("back") != -1) this.delTransformer(that);
    } else transformerNode.detach();
   

    // that.tr.find(".top-left").fillPriority("pattern");
  },
  //删除变换器
  delTransformer(that) {
    const transformerNode = that.tr;
    transformerNode.detach();
    transformerNode.getLayer().batchDraw();
  },
  //舞台鼠标按下
  stageMousedown(that, e) {
    that.$store.commit("templateStage/CLEARREATLIST", []);
    let name;
    //当前工具组件的名字
    if (e.target.attrs.name == "back")
      name = e.target.parent._nodes[0].attrs.name;
    else name = that.$datatools.fragmentreat(e.target.name());

    //鼠标按下的区域
    //正在记录
    if (name.indexOf("anchor") != -1) {
      name = that.selectedShapeName;
      this.creacteTools(that, name);
      that.$store.commit("templateStage/SELECTEDSHAPENAME", name);
    } else if (name == "") {
      this.creacteTools(that, false);
      that.$store.commit("templateStage/SELECTEDSHAPENAME", "");
    } else {
      this.creacteTools(that, name);
      that.$store.commit("templateStage/SELECTEDSHAPENAME", name);
    }

    const clickedOnTransformer =
      e.target.getParent().className === "Transformer";
    if (e.target === e.target.getStage()) {
      !that.isAddLine &&
        that.$store.commit("templateStage/SELECTEDSHAPENAME", "");
      return;
    }
    if (clickedOnTransformer) return;
    const rect = that.textNode;
    if (rect) {
      that.$store.commit("templateStage/SELECTEDSHAPENAME", name);
      that.$store.commit("templateStage/CLICKNAMEREACT", name);
      let name1 = that.$datatools.fragmentreat(name);
      let name2 = that.$datatools.fragmentreat(that.clickname);
      if (name1 == name2) that.$store.commit("templateStage/CLEARREATLIST", []);
    } else {
      // !that.isAddLine &&
      //   that.$store.commit("templateStage/SELECTEDSHAPENAME", "");
    }
    if (name.indexOf("back") != -1)
      that.$store.commit("templateStage/SELECTEDSHAPENAME", "");
    this.updateTransformer(that, name);
  },
  stageblank(that, e) {
    const clickedOnTransformer =
      e.target.getParent().className === "Transformer";
    if (clickedOnTransformer) return;
    const rect = that.textNode;
    if (rect) that.selectedShapeName = name;
    else {
      !that.isAddLine &&
        that.$store.commit("templateStage/SELECTEDSHAPENAME", "");
    }
  },
  //计算屏幕大小
  Screensize(that, maxW, maxH) {
    let backSize;
    //都大于宽高
    if (maxW < that.imgW && maxW < that.imgH) {
      if (that.imgW > that.imgH) backSize = maxW / that.imgW;
      else backSize = maxH / that.imgH;
      //其中一个大于最大边
    } else if (maxW < that.imgW || maxH < that.imgH) {
      if (that.imgW > maxW) backSize = maxW / that.imgW;
      else if (that.imgH > maxH) backSize = maxH / that.imgH;
      //都不大于最大边
    } else backSize = 1;
    that.$store.commit("templateStage/CONKONVA", backSize);
    // this.Refreshstagecontent(that);
  },
  //刷新舞台内容
  Refreshstagecontent(that) {
    //刷新 图片、文本、图片框
    that.listImg.forEach((v) => {
      this.loadele(that, v.config.name);
    });
    that.listNote.forEach((v) => {
      this.loadele(that, v.config.name);
    });
    that.listEllipse.forEach((v) => {
      this.loadele(that, v.config.name);
    });
    that.listlogo.forEach((v) => {
      this.loadele(that, v.config.name);
    });
  },
  loadele(that, childValue) {
    that.$nextTick(() => {
      const node = that.$refs[childValue][0].getStage();
      node.cache();
      node.getLayer().batchDraw();
    });
  },
  //计算屏幕大小
  CalculateScreensize(that, maxW, maxH) {
    let backSize;
    //都大于宽高
    if (maxW < that.imgW && maxW < that.imgH) {
      if (that.imgW > that.imgH) backSize = maxW / that.imgW;
      else backSize = maxH / that.imgH;
      //其中一个大于最大边
    } else if (maxW < that.imgW || maxH < that.imgH) {
      if (that.imgW > maxW) backSize = maxW / that.imgW;
      else if (that.imgH > maxH) backSize = maxH / that.imgH;
      //都不大于最大边
    } else backSize = 1;
    that.$store.commit("templateStage/CONFIGKONVA", backSize);
    this.Refreshstagecontent(that);
  },
  //鼠标进入元素
  stageMouseenter(that, e) {
    let color = "#87ceeb";
    let name = that.$datatools.fragmentreat(e.target.name());
    //是否被上锁
    if (that.keyele.includes(name)) color = "red";
    if (name.indexOf("back") != -1) return;
    else {
      let width = that.$datatools.deepcopy(e.target.width());
      let height = that.$datatools.deepcopy(e.target.height());
      let x = that.$datatools.deepcopy(e.target.x());
      let y = that.$datatools.deepcopy(e.target.y());
      let scaleX = that.$datatools.deepcopy(e.target.scaleX());
      let scaleY = that.$datatools.deepcopy(e.target.scaleY());
      let offsetX = that.$datatools.deepcopy(e.target.offsetX());
      let offsetY = that.$datatools.deepcopy(e.target.offsetY());
      let rotation = that.$datatools.deepcopy(e.target.rotation());
      if (name.indexOf("ellipse") != -1) {
        x = x - (width * scaleX) / 2;
        y = y - (height * scaleY) / 2;
      }
      let new_reat = {
        config: {
          width: width * scaleX,
          height: height * scaleY,
          draggable: false,
          name: `reat${e.target.name()}`,
          x,
          y,
          stroke: color,
          strokeWidth: 3,
          padding: 10,
          offsetX,
          offsetY,
          rotation,
          zIndex: -999,
        },
      };
      that.$store.commit("templateStage/PUSHLISTRECT", new_reat);
    }
  },
  // 添加上锁元素红色外框
  Lockelebox(that, value) {
    let obj;
    if (value.indexOf("con") != -1) {
      that.listNote.forEach((v) => {
        if (v.config.name == value) return (obj = v.config);
      });
    } else if (value.indexOf("img") != -1) {
      that.listImg.forEach((v) => {
        if (v.config.name == value) return (obj = v.config);
      });
    } else if (value.indexOf("ellipse") != -1) {
      that.listEllipse.forEach((v) => {
        if (v.config.name == value) return (obj = v.config);
      });
    }
    let red_box = {
      config: {
        width: that.$datatools.deepcopy(Number(obj.width)),
        height: that.$datatools.deepcopy(Number(obj.height)),
        draggable: false,
        name: `box${obj.name}`,
        x: that.$datatools.deepcopy(Number(obj.x)),
        y: that.$datatools.deepcopy(Number(obj.y)),
        stroke: "red",
        strokeWidth: 4,
        padding: 5,
        offsetX: that.$datatools.deepcopy(
          Number(obj.offsetX ? obj.offsetX : 1)
        ),
        offsetY: that.$datatools.deepcopy(
          Number(obj.offsetY ? obj.offsetY : 1)
        ),
        rotation: that.$datatools.deepcopy(
          Number(obj.rotation ? obj.rotation : 1)
        ),
      },
    };

    that.$store.commit("templateStage/KEYBOXADD", red_box);
  },
  //双击出现文本框
  // editTextDblclick(that, e) {
  //   that.$store.commit(
  //     "templateStage/TEXTNODE",
  //     that.$refs[e.target.attrs.name][0].getNode()
  //   );
  //   that.textNode.hide();
  //   that.tr.hide();
  //   var textPosition = that.textNode.absolutePosition();
  //   var stageBox = that.stage.container().getBoundingClientRect();
  //   var areaPosition = {
  //     x: stageBox.left + textPosition.x,
  //     y: stageBox.top + textPosition.y,
  //   };
  //   var textarea = document.createElement("div");
  //   document.body.appendChild(textarea);
  //   let val = that.textNode.text();
  //   if (val == "双击编辑文本") {
  //     val = "";
  //   }
  //   textarea.setAttribute("contenteditable", "true");
  //   textarea.textContent = val;
  //   textarea.style.position = "absolute";
  //   textarea.style.top = areaPosition.y + "px";
  //   textarea.style.left = areaPosition.x + "px";
  //   textarea.style.minWidth =
  //     that.textNode.width() - that.textNode.padding() * 2 + "px";
  //   textarea.style.height =
  //     that.textNode.height() - that.textNode.padding() * 2 + 5 + "px";
  //   textarea.style.fontSize = that.textNode.fontSize() + "px";
  //   textarea.style.border = "none";
  //   textarea.style.padding = "0px";
  //   textarea.style.margin = "0px";
  //   textarea.style.overflow = "hidden";
  //   textarea.style.background = "none";
  //   textarea.style.outline = "none";
  //   textarea.style.resize = "none";
  //   textarea.style.lineHeight = that.textNode.lineHeight();
  //   textarea.style.fontFamily = that.textNode.fontFamily();
  //   textarea.style.transformOrigin = "left top";
  //   textarea.style.textAlign = that.textNode.align();
  //   textarea.style.color = that.textNode.fill();
  //   // textarea.style. = that.textNode.fill();
  //   var rotation = that.textNode.rotation();
  //   var transform = "";
  //   if (rotation) {
  //     transform += "rotateZ(" + rotation + "deg)";
  //   }
  //   var px = 0;
  //   var isFirefox = navigator.userAgent.toLowerCase().indexOf("firefox") > -1;
  //   if (isFirefox) {
  //     px += 2 + Math.round(that.textNode.fontSize() / 20);
  //   }
  //   transform += "translateY(-" + px + "px)";
  //   textarea.style.transform = transform;
  //   textarea.style.height = "auto";
  //   // after browsers resized it we can set actual value
  //   textarea.style.height = textarea.scrollHeight + 3 + "px";
  //   textarea.focus();
  //   function removeTextarea() {
  //     textarea.parentNode.removeChild(textarea);
  //     window.removeEventListener("click", handleOutsideClick);
  //     that.textNode.show();
  //     that.tr.show();
  //     that.tr.forceUpdate();
  //     that.layer.draw();
  //   }

  //   function setTextareaWidth(newWidth) {
  //     if (!newWidth) {
  //       newWidth = this.textNode.placeholder.length * this.textNode.fontSize();
  //     }
  //     var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  //     var isFirefox = navigator.userAgent.toLowerCase().indexOf("firefox") > -1;
  //     if (isSafari || isFirefox) {
  //       newWidth = Math.ceil(newWidth);
  //     }

  //     var isEdge = document.documentMode || /Edge/.test(navigator.userAgent);
  //     if (isEdge) {
  //       newWidth += 1;
  //     }
  //     textarea.style.width = newWidth + "px";
  //   }
  //   // textarea.addEventListener("keydown", function (e) {
  //   //   if (e.keyCode === 13 && !e.shiftKey) {
  //   //     if (textarea.value == "") {
  //   //       textarea.value = "双击编辑文本";
  //   //     }
  //   //     that.textNode.text(textarea.value);
  //   //     //removeTextarea();
  //   //   }
  //   //   if (e.keyCode === 27) {
  //   //     removeTextarea();
  //   //   }
  //   // });
  //   textarea.addEventListener("keydown", function () {
  //     var scale = that.textNode.getAbsoluteScale().x;
  //     setTextareaWidth(that.textNode.width() * scale);
  //     textarea.style.height = "auto";
  //     textarea.style.width = "auto";

  //     // textarea.style.height =
  //     //   textarea.scrollHeight + that.textNode.fontSize() + "px";
  //   });
  //   function handleOutsideClick(e) {
  //     if (e.target !== textarea) {
  //       if (textarea.value == "") {
  //         textarea.value = "双击编辑文本";
  //       }
  //       that.textNode.text(textarea.textContent);
  //       that.textNode.height(textarea.scrollHeight);
  //       that.textNode.width(textarea.scrollWidth);
  //       removeTextarea();
  //     }
  //   }
  //   setTimeout(() => {
  //     window.addEventListener("click", handleOutsideClick);
  //   });
  // },
  creacteToolstool(that, list, name, store) {
    list.forEach((v) => {
      if (v.config.name == name) that.$store.commit(store, v.config);
    });
  },
  //点击舞台元素
  creacteTools(that, name) {
    that.picturebox = false;
    that.picture = false;
    that.text = false;
    that.datacolor = false;
    that.logo = false;
    that.tempicture = false;
    that.layers = false;
    if (name.indexOf("back") != -1) {
      that.layers = true;
      return;
    } else {
      if (name.indexOf("data") != -1) {
        this.creacteToolstool(
          that,
          that.listNote,
          name,
          "templateStage/DATATOOL"
        );
        that.datacolor = true;
      } else if (name.indexOf("logo") != -1) {
        this.creacteToolstool(
          that,
          that.listlogo,
          name,
          "templateStage/LOGOTOOL"
        );
        that.logo = true;
      } else if (name.indexOf("text") != -1) {
        this.creacteToolstool(
          that,
          that.listNote,
          name,
          "templateStage/LISTNOTETOOL"
        );
        that.text = true;
      } else if (name.indexOf("img") != -1) {
        this.creacteToolstool(
          that,
          that.listImg,
          name,
          "templateStage/IMGTOOL"
        );
        that.picture = true;
      } else if (name.indexOf("ellipse") != -1) {
        this.creacteToolstool(
          that,
          that.listEllipse,
          name,
          "templateStage/ELLIPSETOOL"
        );
        that.picturebox = true;
      }
    }
  },
  //更新元素
  //图片工具-更新元素
  picturetoolloadele(that, childValue) {
    const node = that.$refs[childValue][0].getStage();
    node.cache();
    node.getLayer().batchDraw();
  },
  //处理后端传过来的舞台数据 - 并清空舞台数据
  templateAnalysisOfData(that, data) {
    let _this = this;
    this.ClearingVuex(that);
    //舞台中包含的元素个数
    var numberRefs = 0;
    //图片
    let picnum = 0;
    //上锁的元素
    let arrkey = [];
    let name;
    that.container = true;
    that.$store.commit("templateStage/PROSCENIUM", true); //是否开启舞台
    //重新计算最适合舞台的大小
    data.materialObj.forEach((v) => {
      if (v.name.indexOf("back") != -1) {
        //创建画布-原始的画布大小
        that.$store.commit("templateStage/IMGW", v.w);
        that.$store.commit("templateStage/IMGH", v.h);
      }
    });
    this.Screensize(that, that.maxW, that.maxH);
    function materialobj(arr, index) {
      let v = arr[index];
      let img = new Image();
      img.onload = function () {
        let filters = [];
        v.filters.forEach((v1) => {
          if (v1 == "Brighten" || v1 == "s")
            filters.push(Konva.Filters.Brighten);
          else if (v1 == "Grayscale" || v1 == "i")
            filters.push(Konva.Filters.Grayscale);
        });
        if (v.name.indexOf("back") != -1) {
          v.picname = "背景";
          name = "back";
        } else if (v.name.indexOf("pic") != -1) {
          picnum = picnum + 1;
          name = "pic";
          if (v.picname == "") v.picname = "本地图片";
        } else v.picname = null;
        let new_img = {
          config: {
            width: v.w,
            height: v.h,
            w: v.w,
            h: v.h,
            x: v.x,
            y: v.y,
            draggable: v.draggable,
            name: `img${name}${index}`,
            image: img,
            opacity: v.opacity,
            strokeEnabled: v.strokeEnabled,
            filters,
            brightness: v.brightness,
            s: that.backSize,
            picname: v.picname,
            z: v.z,
            scaleX: v.scaleX,
            scaleY: v.scaleY,
          },
        };
        if (!new_img.config.draggable) arrkey.push(new_img.config.name);
        that.$store.commit("templateStage/PUSHLISTIMG", new_img);
        that.$nextTick(() => {
          const node = that.$refs[new_img.config.name][0].getStage();
          node.cache();
          node.getLayer().batchDraw();
          if (index == data.materialObj.length - 1)
            _this.BelowBackgroundLayer(that);
          else materialobj(data.materialObj, index + 1);
        });
      };
      img.crossOrigin = "Anonymous";
      img.src = v.image;
    }
    materialobj(data.materialObj, 0);
    numberRefs = numberRefs + data.materialObj.length;
    //logo
    if (data.logoObj) {
      for (let [i, v] of data.logoObj.entries()) {
        let img = new Image();
        img.onload = function () {
          let new_logo = {
            config: v,
          };
          new_logo.config.name = `imglogo${i}`;
          new_logo.config.image = img;
          new_logo.config.width = v.w;
          new_logo.config.height = v.h;
          // new_logo.config.s = that.backSize;
          new_logo.config.x = v.x;
          new_logo.config.y = v.y;
          if (
            new_logo.config.picname == "" ||
            new_logo.config.picname == undefined
          )
            new_logo.config.picname = "本地图片";
          new_logo.config.filters = [Konva.Filters.Brighten];
          if (!new_logo.config.draggable) arrkey.push(new_logo.config.name);
          that.$store.commit("templateStage/PUSHLISTLOGO", new_logo);
        };
        img.crossOrigin = "Anonymous";
        img.src = v.image;
      }
    }
    numberRefs = numberRefs + data.logoObj.length;
    function textObj(arr, index) {
      let v = arr[index];
      let new_text = {
        config: v,
      };
      let type;
      let text;
      if (v.name.indexOf("text") > -1) {
        type = "text";
        text = v.text;
      } else if (v.name.indexOf("data") > -1) {
        type = "data";
        text = that.$datatools.formattime();
      } else new_text.config.name = `con${type}${numberRefs + index}`;
      new_text.config.text = text;
      if (!new_text.config.draggable) arrkey.push(new_text.config.name);
      that.$store.commit("templateStage/PUSHLISTNOTE", new_text);
      if (index == data.textObj.length - 1) return;
      else textObj(data.textObj, index + 1);
    }
    //text
    if (data.textObj.length > 0) textObj(data.textObj, 0);
    numberRefs = numberRefs + data.textObj.length;
    //imgbox
    if (data.imgBoxObj) {
      data.imgBoxObj.forEach((v, i) => {
        numberRefs++;
        let new_imgbox = {
          config: v,
        };
        new_imgbox.config.name = `ellipse${numberRefs + i}`;
        if (!new_imgbox.config.draggable) arrkey.push(new_imgbox.config.name);
        that.$store.commit("templateStage/PUSHLISTELLIPSE", new_imgbox);
      });
    }
    numberRefs = numberRefs + data.imgBoxObj.length;
    that.$store.commit("templateStage/REASETNUMBERREFS", numberRefs);
    that.$store.commit("templateStage/REASETKEYELE", arrkey);
    that.$store.commit(
      "templateStage/REASETIMGNUM",
      data.materialObj.length - 1
    );
    that.$store.commit("templateStage/KONVAID", data.templateId); //出现在舞台上模板id
    that.$store.commit("templateStage/KONVANAME", data.templateName); //出现在舞台上模板name
    that.$store.commit("templateStage/KONVATEXT", {
      onelevel: data.firstType,
      twolevel: data.secondType,
      threelevel: data.tagIds,
    }); //出现在舞台上模板id

    that.$store.commit("templateStage/HISTORY");
    that.$nextTick(() => {
      that.layer.draw();
      that.layers = true;
      that.picturebox = false;
      that.picture = false;
      that.text = false;
      that.datacolor = false;
      that.logo = false;
      that.loadingframe = false;
      that.maskframe = false;
      that.$createstage.delTransformer(that);
      that.$store.commit("templateStage/HISTORY");
    });
  },
  BelowBackgroundLayer(that) {
    //LISTKEYELE
    //素材在背景下方
    let index;
    that.listImg.forEach((v, i) => {
      if (v.config.name.indexOf("back") > 0) index = i;
    });
    that.listImg.forEach((v, i) => {
      if (i < index) that.afterbackimg.push(v.config.name);
    });
  },
  //清空状态管理
  ClearingVuex(that) {
    that.$store.commit("templateStage/KONVAID", null);
    that.$store.commit("templateStage/KONVATEXT", {
      onelevel: "",
      twolevel: "",
      threelevel: "",
    });
    that.$store.commit("templateStage/IMGW", null);
    that.$store.commit("templateStage/IMGH", null);
    that.$store.commit("templateStage/REASETNUMBERREFS", null);
    that.$store.commit("templateStage/LISTLOGONULL", []);
    that.$store.commit("templateStage/LISTNOTENULL", []);
    that.$store.commit("templateStage/LISTELLIPSENULL", []);
    that.$store.commit("templateStage/LISTIMGNULL", []);
    that.$store.commit("templateStage/KEYBOXNULL", []);
    that.$store.commit("templateStage/SELECTEDSHAPENAME", "");
    that.$store.commit("templateStage/CANCELNAME", "");
    that.$store.commit("templateStage/REASETIMGNUM", 0);
    that.$store.commit("templateStage/UPDATELENULL", 0);
    that.$store.commit("templateStage/MODIFYELE", null);
    that.$store.commit("templateStage/REASETKEYELE", []);
    that.$store.commit("templateStage/PROSCENIUM", false);
    that.$store.commit("templateStage/KONVANAME", "");
    that.$store.commit("templateStage/HISTORY");
    that.afterbackimg = [];
  },
  //复制当前选中的图片
  copymodifyele(that) {
    //素材 文字
    if (that.historylist.length == 0) that.$createstage.saveHistory(that);
    //imgpic context2
    let type;
    if (that.modifyele.indexOf("imgpic") != -1) {
      that.$store.commit("templateStage/COPYLISTING", that.modifyele);
      type = "imgpic";
    } else if (that.modifyele.indexOf("context") != -1) {
      that.$store.commit("templateStage/COPYLISTNOTE", that.modifyele);
      type = "context";
    } else if (that.modifyele.indexOf("imglogo") != -1) {
      that.$store.commit("templateStage/COPYLISTLOGO", that.modifyele);
      type = "imglogo";
    }
    setTimeout(() => {
      that.$nextTick(() => {
        let name_refs;
        let name;
        if (type == "imgpic") {
          // let name_refs=this.listImg[this.listImg.length]
          let numberImg = that.listImg.length - 1;
          name_refs =
            that.$refs[that.listImg[numberImg].config.name][0].getNode();
          name_refs.cache();
          name_refs.getLayer().batchDraw();
          name = that.listImg[numberImg].config.name;
        } else if (type == "context") {
          let numberImg = that.listNote.length - 1;
          name_refs =
            that.$refs[that.listNote[numberImg].config.name][0].getNode();
          name = that.listNote[numberImg].config.name;
        } else if (type == "imglogo") {
          let numberImg = that.listlogo.length - 1;
          name_refs =
            that.$refs[that.listlogo[numberImg].config.name][0].getNode();
          name = that.listlogo[numberImg].config.name;
        }
        that.$createstage.addTransformerImmediate(that, name_refs, name);
        that.$createstage.saveHistory(that);
        that.$message("复制成功");
      });
    }, 200);
  },
  delmodifyele(that) {
    if (that.modifyele.indexOf("imgpic") != -1) {
      that.listImg.forEach((v, index) => {
        if (v.config.name == that.modifyele)
          that.$store.commit("templateStage/DELLISTIMG", index);
      });
      this.picture = false;
    } else if (that.modifyele.indexOf("context") != -1) {
      that.listNote.forEach((v, index) => {
        if (v.config.name == that.modifyele)
          that.$store.commit("templateStage/TEXTDELLISTIMG", index);
      });
      this.text = false;
    } else if (that.modifyele.indexOf("imglogo") != -1) {
      that.listlogo.forEach((v, index) => {
        if (v.config.name == that.modifyele)
          that.$store.commit("templateStage/LOGODELLISTIMG", index);
      });
      this.logo = false;
    }
    this.delTransformer(that);
  },
  // Text保存历史记录
  saveTextHistory(that, property, value, name) {
    function material(copyarr, newarr) {
      let arr = [];
      newarr.forEach((v, i) => {
        v.config.image = copyarr[i].config.image.src;
        copyarr[i].config.filters.forEach((item) => {
          arr.push(item.name);
        });
        v.config.filters = arr;
        arr = [];
      });
    }
    let listlogo = JSON.parse(JSON.stringify(that.listlogo));
    let listImg = JSON.parse(JSON.stringify(that.listImg));
    material(that.listlogo, listlogo);
    material(that.listImg, listImg);
    let text = JSON.parse(JSON.stringify(that.listNote));
    text.forEach((v) => {
      if (v.config.name == name) {
        if (property == "shadowOffsetY") v.config.shadowOffsetY = value;
        if (property == "shadowOffsetX") v.config.shadowOffsetX = value;
        if (property == "shadowBlur") v.config.shadowBlur = value;
        if (property == "shadowColor") v.config.shadowColor = value;
        if (property == "fill") v.config.fill = value;
        if (property == "stroke") v.config.stroke = value;
        if (property == "strokeWidth") v.config.strokeWidth = value;
      }
    });
    let objInitialize = {
      logo: listlogo,
      pic: listImg,
      picbox: JSON.parse(JSON.stringify(that.listEllipse)),
      text,
    };
    let arr = JSON.stringify(objInitialize);
    that.$store.commit("templateStage/HISTORYLIST", arr);
  },
  //保存历史记录
  saveHistory(that) {
    function material(copyarr, newarr) {
      let arr = [];
      newarr.forEach((v, i) => {
        v.config.image = copyarr[i].config.image.src;
        copyarr[i].config.filters.forEach((item) => {
          arr.push(item.name);
        });
        v.config.filters = arr;
        arr = [];
      });
    }
    let listlogo = JSON.parse(JSON.stringify(that.listlogo));
    let listImg = JSON.parse(JSON.stringify(that.listImg));
    material(that.listlogo, listlogo);
    material(that.listImg, listImg);
    let objInitialize = {
      logo: listlogo,
      pic: listImg,
      picbox: JSON.parse(JSON.stringify(that.listEllipse)),
      text: JSON.parse(JSON.stringify(that.listNote)),
    };
    let arr = JSON.stringify(objInitialize);
    that.$store.commit("templateStage/HISTORYLIST", arr);
  },
  //展示历史记录
  showHistory(that) {
    this.delTransformer(that);
    that.$store.commit("templateStage/LISTLOGONULL", []);
    that.$store.commit("templateStage/LISTNOTENULL", []);
    that.$store.commit("templateStage/LISTELLIPSENULL", []);
    that.$store.commit("templateStage/LISTIMGNULL", []);
    let page = that.historycurrentpage - 1;
    let obj = JSON.parse(that.historylist[page]);
    let { logo, pic, picbox, text } = obj;
    let arrkey = [];
    function materialobj(arr, index, store) {
      let v = JSON.parse(JSON.stringify(arr[index]));
      let img = new Image();
      img.onload = function () {
        let filters = [];
        v.config.filters.forEach((v1) => {
          if (v1 == "Brighten" || v1 == "s")
            filters.push(Konva.Filters.Brighten);
          else if (v1 == "Grayscale" || v1 == "i")
            filters.push(Konva.Filters.Grayscale);
        });
        if (v.config.name.indexOf("back") > 1)
          v.config.name = `imgback${index}`;
        else if (v.config.name.indexOf("pic") > 1)
          v.config.name = `imgpic${index}`;
        else if (v.config.name.indexOf("logo") > 1)
          v.config.name = `imglogo${index}`;
        v.config.filters = filters;
        v.config.image = img;
        that.$store.commit(`templateStage/${store}`, v);
        that.$nextTick(() => {
          const node = that.$refs[v.config.name][0].getStage();
          node.cache();
          node.getLayer().batchDraw();
        });
        if (!v.config.draggable) arrkey.push(v.config.name);
        if (index == arr.length - 1) return;
        else materialobj(arr, index + 1, store);
      };
      img.crossOrigin = "Anonymous";
      img.src = v.config.image;
    }
    if (logo.length == 0) logo = [];
    else materialobj(logo, 0, "PUSHLISTLOGO");
    materialobj(pic, 0, "PUSHLISTIMG");
    function draggable(arr, index) {
      let v = arr[index];
      if (!v.config.draggable) arrkey.push(v.config.name);
      if (v.config.name.indexOf("data") > 1) v.config.name = `condata${index}`;
      else if (v.config.name.indexOf("text") > 1)
        v.config.name = `context${index}`;
      else if (v.config.name.indexOf("ellipse") > 1)
        v.config.name = `ellipse${index}`;
    }
    if (picbox.length == 0) picbox = [];
    else draggable(picbox, 0);
    if (text.length == 0) text = [];
    else draggable(text, 0);
    let numberRefs = logo.length + pic.length + picbox.length + text.length;
    that.$store.commit("templateStage/LISTELLIPSENULL", picbox);
    that.$store.commit("templateStage/LISTNOTENULL", text);
    that.$store.commit("templateStage/REASETKEYELE", arrkey);
    that.$store.commit("templateStage/REASETNUMBERREFS", numberRefs);
  },
  //内容页缓存到本本地
  contentLocalCache(that) {
    localStorage.setItem("contentsave", null);
    let contentsave = {
      templateName: that.konvaname,
      textObj: [],
      materialObj: [],
      imgBoxObj: [],
      logoObj: [],
    };
    function materialobj(arr, index, savearr) {
      let v = arr[index];
      let obj = JSON.parse(JSON.stringify(v.config));
      let filters = [];
      v.config.filters.forEach((v1) => {
        filters.push(v1.name);
        obj.filters = filters;
      });
      obj.image = v.config.image.src;
      savearr.push(obj);
      if (index == arr.length - 1) return;
      else materialobj(arr, index + 1, savearr);
    }
    if (that.listImg.length > 0)
      materialobj(that.listImg, 0, contentsave.materialObj);
    if (that.listlogo.length > 0)
      materialobj(that.listlogo, 0, contentsave.logoObj);
    if (that.listNote.length > 0)
      that.listNote.forEach((v) => {
        contentsave.textObj.push(JSON.parse(JSON.stringify(v.config)));
      });

    if (that.listEllipse.length > 0)
      that.listEllipse.push((v) => {
        contentsave.imgBoxObj.push(JSON.parse(JSON.stringify(v.config)));
      });
    contentsave = JSON.stringify(contentsave);
    localStorage.setItem("contentsave", contentsave);
  },
  getLineGuideStops(skipShape, that) {
    let vertical = [0, that.stage.width() / 2, that.stage.width()];
    let horizontal = [0, that.stage.height() / 2, that.stage.height()];
    that.stage.find("Image,Text").forEach((guideItem) => {
      if (guideItem === skipShape) return;
      let box = guideItem.getClientRect({ relativeTo: that.stage });
      // vertical.push([box.x, box.x + box.width, box.x + box.width / 2]);
      horizontal.push([box.y, box.y + box.height, box.y + box.height /2 ]);
    });
    return {
      vertical: vertical.flat(),
      horizontal: horizontal.flat(),
    };
  },
  getObjectSnappingEdges(node, that) {
    let box = node.getClientRect({ relativeTo: that.stage });
    return {
      vertical: [
        {
          guide: Math.round(box.x),
          offset: Math.round(node.x() - box.x),
          snap: "start",
        },
        {
          guide: Math.round(box.x + box.width / 2),
          offset: Math.round(node.x() - box.x - box.width / 2),
          snap: "center",
        },
        {
          guide: Math.round(box.x + box.width),
          offset: Math.round(node.x() - box.x - box.width),
          snap: "end",
        },
      ],
      horizontal: [
        {
          guide: Math.round(box.y+18),
          offset: Math.round(node.y() - box.y+18),
          snap: "start",
        },
        {
          guide: Math.round(box.y + box.height / 2),
          offset: Math.round(node.y() - box.y - box.height / 2),
          snap: "center",
        },
        {
          guide: Math.round(box.y + box.height-2),
          offset: Math.round(node.y() - box.y - box.height-2),
          snap: "end",
        },
      ],
    };
  },
  drawGuides(guides, that) {
    guides.forEach((lg) => {
      let obj = {};
      if (lg.orientation === "H") {
        obj.points = [-6000, lg.lineGuide, 6000, lg.lineGuide];
        obj.stroke = "red";
        obj.strokeWidth = 1;
        obj.name = "guid-line";
        obj.dash = [4, 6];
      } else if (lg.orientation === "V") {
        obj.points = [lg.lineGuide, -6000, lg.lineGuide, 6000];
        obj.stroke = "red";
        obj.strokeWidth = 1;
        obj.name = "guid-line";
        obj.dash = [4, 6];
      }
      that.assistline.push(obj);
      that.layer.batchDraw();
    });
  },
  getGuides(lineGuideStops, itemBounds, that) {
    let resultV = [];
    let resultH = [];
    lineGuideStops.vertical.forEach((lineGuide) => {
      itemBounds.vertical.forEach((itemBound) => {
        let diff = Math.abs(lineGuide - itemBound.guide);
        // if the distance between guild line and object snap point is close we can consider this for snapping
        if (diff < that.GUIDELINE_OFFSET) {
          resultV.push({
            lineGuide: lineGuide,
            diff: diff,
            snap: itemBound.snap,
            offset: itemBound.offset,
          });
        }
      });
    });

    lineGuideStops.horizontal.forEach((lineGuide) => {
      itemBounds.horizontal.forEach((itemBound) => {
        let diff = Math.abs(lineGuide - itemBound.guide);
        if (diff < that.GUIDELINE_OFFSET) {
          resultH.push({
            lineGuide: lineGuide,
            diff: diff,
            snap: itemBound.snap,
            offset: itemBound.offset,
          });
        }
      });
    });

    let guides = [];
    // find closest snap
    let minV = resultV.sort((a, b) => a.diff - b.diff)[0];
    let minH = resultH.sort((a, b) => a.diff - b.diff)[0];
    if (minV) {
      guides.push({
        lineGuide: minV.lineGuide,
        offset: minV.offset,
        orientation: "V",
        snap: minV.snap,
      });
    }
    if (minH) {
      guides.push({
        lineGuide: minH.lineGuide,
        offset: minH.offset,
        orientation: "H",
        snap: minH.snap,
      });
    }
    return guides;
  },
};
